/*
 * connion_mgr.h
 *
 *  Created on: Aug 1, 2013
 *      Author: killerg
 */

#ifndef connION_MGR_H_
#define connION_MGR_H_

#include <list>
#include <map>
#include <mutex>
#include <functional>

#include "patterns.h"
#include "util.h"

template<typename TransT, typename ConnT>
struct connection_mgr {
    connection_mgr() {
        valid_sessid = 0;
    }

    ptr_map<int64_t, ConnT*> map_id;
    ptr_map<TransT*, ConnT*> map_trans;
    std::mutex lock;
    int64_t valid_sessid;

    void create_conn(TransT* trans) {
        std::lock_guard<std::mutex> g(lock);
        auto conn = new ConnT(valid_sessid++, trans);
        map_trans.set(trans, conn);
        map_id.set(conn->_sessid, conn);
        conn->on_connect();
    }

    void delete_conn(TransT* trans) {
        std::lock_guard<std::mutex> g(lock);
        auto conn = map_trans.get(trans);
        if (NULL != conn) {
            int64_t sessid = conn->_sessid;
            conn->on_disconnect();
            safe_del(conn);
            map_trans.erase(trans);
            map_id.erase(sessid);
        }
    }

    // reserve
    void update() {
        map_trans.for_each([](TransT* trans, ConnT* &conn){
            conn->update();
        });
    }

    int32_t size() {
        return map_trans.size();
    }

};


#endif /* CONNECTION_MGR_H_ */
